package com.thinksns.sociax.t4.android.event;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.thinksns.sociax.android.R;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.listener.BlankTextSwitcher;
import com.thinksns.sociax.t4.adapter.AdapterEventComment;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.android.popupwindow.PopupWindowListDialog;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.component.SmallDialog;
import com.thinksns.sociax.t4.model.ModelComment;
import com.thinksns.sociax.t4.model.ModelEventNotifyComment;
import com.thinksns.sociax.thinksnsbase.activity.widget.ListFaceView;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;
import com.thinksns.sociax.thinksnsbase.utils.UnitSociax;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class EventDetailCommentActivity extends ThinksnsAbscractActivity implements View.OnClickListener, AdapterView.OnItemClickListener, OnRefreshListener, OnLoadmoreListener {

    private SmartRefreshLayout smartRefreshLayout;
    private ImageView imgFace;
    private EditText etComment;
    private Button btnSendComment;
    private ListFaceView faceView;
    private LinearLayout llComment;
    private ListView mListView;
    private SmallDialog dialog;

    private AdapterEventComment commentAdapter;
    private ModelExpandComment modelComments; //评论列表包含在里面
    private String eid;
    private String to_uid, to_comment_id, to_uname; //回复别人的id
    private int currentPage = 1;
    private int mMinId = 0;
    private EventDetailCommentPresenter mPresenter;
    protected boolean actAlive = true;
    private PopupWindowListDialog.Builder builder;

    @Override
    public String getTitleCenter() {
        return "活动评论";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initIntentData();
        initView();
        initListener();
        initData();
    }

    private void initIntentData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            throw new AssertionError("intent no data!");
        } else {
            eid = bundle.getString("eid");
        }
    }

    private void initView() {
        this.smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.smart_refresh_layout);
        this.llComment = (LinearLayout) findViewById(R.id.ll_comment);
        this.faceView = (ListFaceView) findViewById(R.id.face_view);
        this.btnSendComment = (Button) findViewById(R.id.btn_send_comment);
        this.etComment = (EditText) findViewById(R.id.et_comment);
        this.imgFace = (ImageView) findViewById(R.id.img_face);
        faceView.initSmileView(etComment);
        mPresenter = new EventDetailCommentPresenter();
        mListView = (ListView) findViewById(R.id.pull_refresh_list);
        dialog = new SmallDialog(this, "评论中...");
        initListViewAttr();
    }

    @Override
    protected CustomTitle setCustomTitle() {
        return new LeftAndRightTitle(R.drawable.img_back, this);
    }

    private void initListener() {
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadmoreListener(this);
        etComment.addTextChangedListener(new BlankTextSwitcher() {
            @Override
            protected void onTextBlank() {
                btnSendComment.setEnabled(false);
            }

            @Override
            protected void onTextNotBlank() {
                btnSendComment.setEnabled(true);
            }
        });

        btnSendComment.setOnClickListener(this);
        imgFace.setOnClickListener(this);
        etComment.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                etComment.clearFocus();
                faceView.setVisibility(View.GONE);
                imgFace.setImageResource(R.drawable.face_bar);
                UnitSociax.hideSoftKeyboard(EventDetailCommentActivity.this, etComment);
                resetCommentUI();
                return false;
            }
        });
    }

    private void initData() {
        commentAdapter = new AdapterEventComment(this, null);
        mListView.setAdapter(commentAdapter);
        smartRefreshLayout.autoRefresh();
    }

    protected void initListViewAttr() {
        mListView.setDivider(new ColorDrawable(0x72cccccc));
        mListView.setDividerHeight(UnitSociax.dip2px(this, 0.2f));
        mListView.setSelector(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    }

    @Override
    protected void onDestroy() {
        actAlive = false;
        super.onDestroy();
    }

    public void resetCommentUI() {
        to_uid = "";
        imgFace.setImageResource(R.drawable.face_bar);
        faceView.setVisibility(View.GONE);
        etComment.setText("");
        etComment.setHint(getString(R.string.comment_hint_edit));
        etComment.clearFocus();
        UnitSociax.hideSoftKeyboard(this, etComment);
    }

    public void setupCommentUI(ModelEventNotifyComment comment) {
        to_uname = comment.getUname();
        to_uid = comment.getUid() + "";
        to_comment_id = comment.getComment_id() + "";
        imgFace.setImageResource(R.drawable.face_bar);
        faceView.setVisibility(View.GONE);
        etComment.requestFocus();
        etComment.post(new Runnable() {
            @Override
            public void run() {
                UnitSociax.showSoftKeyborad(EventDetailCommentActivity.this, etComment);
            }
        });

        String name = TextUtils.isEmpty(comment.getRemark()) ? comment.getUname() : comment.getRemark();
        etComment.setHint(String.format(getString(R.string.comment_format_reply), name));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_event_detail_comment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send_comment:
                dialog.show();
                if (!TextUtils.isEmpty(to_uid)) { //回复
                    mPresenter.postComment(getString(R.string.replyat) + to_uname + "：" + etComment.getText().toString(), to_uid, to_comment_id);
                } else {
                    mPresenter.postComment(etComment.getText().toString(), to_uid, to_comment_id);
                }
                break;
            case R.id.img_face:
                if (faceView.getVisibility() == View.GONE) {
                    UnitSociax.hideSoftKeyboard(this, etComment);
                    imgFace.setImageResource(R.drawable.key_bar);
                    faceView.setVisibility(View.VISIBLE);
                } else {
                    faceView.setVisibility(View.GONE);
                    imgFace.setImageResource(R.drawable.face_bar);
                    etComment.requestFocus();
                    UnitSociax.showSoftKeyborad(this, etComment);
                }
                break;
            case R.id.et_comment:
                faceView.setVisibility(View.GONE);
                imgFace.setImageResource(R.drawable.face_bar);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (!commentAdapter.getNoData() && id >= 0) {
            ModelEventNotifyComment comment = commentAdapter.getItem((int) id);
            getItemOptions(comment);
//            if (comment.getUid() == Thinksns.getMy().getUid()) {
//                //可能存在处理 点击自己的评论
//                setupCommentUI(comment); //暂时也为回复自己
//            } else { //别人的评论 回复
//                setupCommentUI(comment);
//            }
        }
    }

    // 获取菜单选项
    private void getItemOptions(final ModelEventNotifyComment comment) {
        final boolean isMy = comment.getUid() == Thinksns.getMy().getUid();
        List<String> datas = new ArrayList<String>();
        if (isMy) {
            datas.add("删除");
        } else {
            datas.add("评论");
        }

        datas.add("复制");
        datas.add("取消");

        createOptionsMenu(datas, comment);

    }

    // 创建菜单项
    private void createOptionsMenu(List<String> datas, final ModelEventNotifyComment replyComment) {
        builder = new PopupWindowListDialog.Builder(this);
        builder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (replyComment.getUid() == Thinksns.getMy().getUid()) {
                        // 删除评论
                        deleteComment(replyComment);
                    } else {
                        // 回复评论
                       setupCommentUI(replyComment);
                    }
                } else if (position == 1) {
                    // 复制评论
                    com.thinksns.sociax.t4.unit.UnitSociax.copy(replyComment.getContent(), EventDetailCommentActivity.this);
                }
                builder.dimss();
            }
        });

        builder.create(datas);
    }

    private void deleteComment(final ModelEventNotifyComment replyComment) {
        Thinksns.getApplication().getApiEvent().deleteComment(replyComment.getComment_id(), new ApiHttpClient.HttpResponseListener() {
            @Override
            public void onSuccess(Object result) {
                ToastUtils.showToast(String.valueOf(result));
                commentAdapter.removeItem(replyComment);
                EventBus.getDefault().post(replyComment);
            }

            @Override
            public void onError(Object result) {
                ToastUtils.showToast(String.valueOf(result));
            }
        });
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mMinId = 0;
        mPresenter.loadData( true);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mPresenter.loadData(false);
    }


    private class EventDetailCommentPresenter {
        /**
         * 加载所有评论
         *
         * @param isRefresh
         */
        public void loadData(final boolean isRefresh) {
            ((Thinksns) getApplicationContext()).getApiEvent().getMyComment(eid, mMinId + "", true, new ApiHttpClient.HttpResponseListener() {
                @Override
                public void onSuccess(Object result) {
                    if (actAlive) {
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadmore();
                        dialog.dismiss();
                        if (isRefresh) {
                            to_uid = null;
                            to_comment_id = null;
                            to_uname = null;
                            resetCommentUI();
                            modelComments = (ModelExpandComment) result;
                            if (modelComments.getComment().size() == 0) { //无评论
                                commentAdapter.setNoDataWithFullScreen();
                            } else {
                                mMinId = modelComments.getComment().get(modelComments.getComment().size() - 1).getComment_id();
                                commentAdapter.setHasData();
                                commentAdapter.resetData(modelComments.getComment());
                            }
                        } else {
                            if (modelComments != null) {
                                modelComments = (ModelExpandComment) result;
                                if (modelComments.getComment().size() == 0) { //无评论
                                    commentAdapter.setNoDataWithFullScreen();
                                } else {
                                    mMinId = modelComments.getComment().get(modelComments.getComment().size() - 1).getComment_id();
                                    commentAdapter.setHasData();
                                    commentAdapter.addAll(modelComments.getComment());
                                }
                            }
                        }
                    }
                }

                @Override
                public void onError(Object result) {
                    if (actAlive) {
                        dialog.dismiss();
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadmore();
                        if (!((String) result).equals(getString(R.string.load_fail)) && commentAdapter.getCount() == 0) {
                            commentAdapter.setNoDataWithFullScreen();
                            return;
                        }
                        ToastUtils.showToast((String) result);
                    }
                }
            });
        }

        /**
         * 回复评论
         *
         * @param content
         * @param to_uid
         * @param to_comment_id
         */
        public void postComment(String content, final String to_uid, String to_comment_id) {
            ((Thinksns) getApplicationContext()).getApiEvent().postComment(eid, content, to_uid, to_comment_id,
                    new ApiHttpClient.HttpResponseListener() {
                        @Override
                        public void onSuccess(Object result) {
                            if (actAlive && (Boolean) result) {
                                mMinId = 0;
                                loadData(true);
                                ModelEventNotifyComment comment = new ModelEventNotifyComment();
                                EventBus.getDefault().post(comment);
                                resetCommentUI();
                            }
                        }

                        @Override
                        public void onError(Object result) {
                            if (actAlive) {
                                dialog.dismiss();
                                ToastUtils.showToast((String) result);
                            }
                        }
                    });
        }
    }
}
